package com.lzy.wzy.handle;

import com.lzy.wzy.mapper.UserMapper;
import com.lzy.wzy.token.MyUsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service("el")
public class ElPermissionHandler {


    @Autowired
    private UserMapper userMapper;


    private final static String key="url_authority";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public boolean check(String... role) {
        MyUsernamePasswordToken token = (MyUsernamePasswordToken) SecurityContextHolder.getContext().getAuthentication();
        List<String> list = token.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
//        System.out.println(Arrays.toString(userMapper.queryUrlAuthorityInfo("/index/getName")));
//        System.out.println(Arrays.stream(userMapper.queryUrlAuthorityInfo("/produce/getTemplate").split(",")).anyMatch(list::contains));
//        for (String s : role) {
//            if (list.contains(s)) {
//                return true;
//            }
//        }
        return Arrays.stream(role).anyMatch(list::contains);
    }

    public boolean authentication() {
        MyUsernamePasswordToken token = (MyUsernamePasswordToken) SecurityContextHolder.getContext().getAuthentication();
        String authority = (String) stringRedisTemplate.opsForHash().get(key,token.getUri());
        if (authority == null) {
            authority = userMapper.queryUrlAuthorityInfo(token.getUri());
        }
        List<String> list = token.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        return Arrays.stream(authority.split(",")).anyMatch(list::contains);
    }
}
